#include <iostream> 
#include <string>
#include <memory>
#include <muduo/net/TcpClient.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/EventLoopThread.h>
#include <muduo/net/Buffer.h>
 
class DictClient{
public:
    DictClient(const std::string &ip, int port)
    // 一旦开始事件监听 就会进入死循环 因为客户端这里还需要接收客户输入的信息 所以需要单独用一个线程来进行事件监听
    :_baseloop(_loopthread.startLoop()),      
    _downlatch(1),
    _client(_baseloop, muduo::net::InetAddress(ip, port), "Diciclient")
    {
        _client.setConnectionCallback(std::bind(&DictClient::onConnection, this, std::placeholders::_1));
        _client.setMessageCallback(std::bind(&DictClient::onMessage, this, std::placeholders::_1,
                                             std::placeholders::_2, std::placeholders::_3));

        // 连接服务器
        _client.connect();
        // 同步操作 阻塞等待连接成功
        _downlatch.wait();
    }

    bool send(const std::string &msg){
        if (_conn->connected() == false){
            std::cout << "连接已断开..." << std::endl;
            return false;
        }
        _conn->send(msg);
        return true;
    }

private:
    void onConnection(const muduo::net::TcpConnectionPtr &conn){
        // 判断连接是否建立或断开
        if (conn->connected()){
            std::cout << "连接建立..." << std::endl;
            _conn = conn;
            // 同步计数器减一 减到0时唤醒阻塞
            _downlatch.countDown();
        }
        else{
            std::cout << "连接断开..." << std::endl;
            _conn.reset();
        }
    }

    void onMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buf, muduo::Timestamp){
        std::string res = buf->retrieveAllAsString();
        std::cout << "翻译: " << res << std::endl;
    }

private:
    muduo::net::TcpConnectionPtr _conn;
    muduo::CountDownLatch _downlatch;
    muduo::net::EventLoopThread _loopthread;  // 事件监听线程
    muduo::net::EventLoop *_baseloop;
    muduo::net::TcpClient _client;
};

int main(){
    std::unique_ptr<DictClient> client(new DictClient("127.0.0.1", 28080));
    while(true){
        std::string msg;
        std::cin >> msg;
        bool ret = client->send(msg);
        if (ret == false){
            break;
        }
    }
    return 0;
}